package com.persistencia.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.apache.poi.hssf.record.formula.functions.T;

import com.exceptions.PersistenceException;

public class RecordSerializable extends RecordStrategy {

	public RecordSerializable(Class<T> classType) throws PersistenceException {
		super(classType);
		try {
			FILE_NAME += getClassTypeName() + ".ser";
			createFile();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public synchronized Boolean writeData(List<?> obj)
			throws PersistenceException {

		try {
			FileOutputStream fout = new FileOutputStream(FILE_NAME);
			ObjectOutputStream oos = new ObjectOutputStream(fout);
			oos.writeObject(obj);
			oos.close();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
		return true;

	}

	@SuppressWarnings("unchecked")
	@Override
	public synchronized List<?> readData() throws PersistenceException {
		Object theQueue = null;
		try {
			FileInputStream fin = new FileInputStream(FILE_NAME);
			if (fin.available() == 0) {
				fin.close();
				return null;
			}
			ObjectInputStream ois = new ObjectInputStream(fin);
			theQueue = ois.readObject();
			ois.close();
			fin.close();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}

		return (List<Object>) theQueue;
	}

}
